package com.star.httpclient;

import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.*;

public class PostCookieTest {

    private final HttpClient httpClient = HttpClient.newHttpClient();
    private String url;
    private String cookies;

    @BeforeTest
    public void readProperties() {
        ResourceBundle bundle = ResourceBundle.getBundle("app", Locale.CHINA);
        url = bundle.getString("testUrl");
    }

    @Test
    public void test1() throws IOException, InterruptedException {
        HttpRequest httpRequest = HttpRequest.newBuilder()
                .uri(URI.create(url + "/getCookies"))
                .build();

        HttpResponse<String> response = httpClient.send(
                httpRequest, HttpResponse.BodyHandlers.ofString());

        Assert.assertEquals(response.statusCode(), 200);

        // 获取响应中的 cookies
        List<String> cookiesList = response.headers().allValues("Set-Cookie");
        cookies = String.join("; ", cookiesList);
    }

    @Test(dependsOnMethods = {"test1"})
    public void test2() throws IOException, InterruptedException {
        // JSON 数据
        String json = "{\"username\":\"star\", \"password\":\"123456\"}";

        HttpRequest httpRequest = HttpRequest.newBuilder()
                .uri(URI.create(url + "/postWithCookies")) // 替换为实际的 POST 请求 URL
                .header("Content-Type", "application/json") // 设置 Content-Type
                .header("Cookie", cookies) // 手动添加 Cookie 头
                .POST(HttpRequest.BodyPublishers.ofString(json)) // 添加 JSON 数据
                .build();

        HttpResponse<String> response = httpClient.send(
                httpRequest, HttpResponse.BodyHandlers.ofString());

        System.out.println("响应状态码：" + response.statusCode());
        System.out.println("响应体：" + response.body());
    }
}
